﻿<?php
// $Id$

/**
 * Controller_Article 控制器
 */
require '_code/lib/utils.php';
require '_code/lib/constant.php';

class Controller_Article extends Controller_Abstract
{
    function getEnterpriseAuditStatus($user)
    {
        $enterprise_setting = Enterprisesetting::find('enterprise_id = ?', $user->enterprise_id)->getOne();
        return $enterprise_setting->audit_open_or_not;
    }

    function actionAudit()
    {
        if(null == $this->_app->currentUser())
        {
            return $this->_redirect(url('default/index'));
        }
        if ($this->_context->isPost())
        {
            $article_id = $_POST['aid'];
            $user = $this->_app->currentUserObject();
            $result = $_POST['result'];
            $reason = $_POST['reason'];

            $article = Article::find('article_id = ?', $article_id)->getOne();
            $article->audit_user_id = $user->user_id;

            if ($result == "pass") $result = 4;
            if ($result == "fail") 
            {
                $result = 5;
                $article->article_reject_reason = $reason;
            }
            
            $article->article_status = $result;
            $article->save();
            return $this->_redirectMessage(
                '文章审核',
                '文章已经成功审核',
                url('article/index'));
        }
    }

    function actionRejectIndex()
    {
        if(null == $this->_app->currentuser())
        {
            return $this->_redirect(url('default/index'));
        }
        $current_user = $this->_app->currentUserObject();
        $articles = Article::find('enterprise_id = ? and article_status = 5', 
            $current_user->user_id)->order('article_create_timestamp desc');
        $column_ids = Article::find("enterprise_id = ?", $current_user->enterprise_id)->setColumns("column_id")->asArray()->distinct()->getAll();
        $columns = Array(); 
        foreach($column_ids as $column_id)
        {
            $column = Column::find('column_id = ?', $column_id)->getOne();
            $columns[$column_id['column_id']] = $column->column_name;
        }
        $this->_view['columns'] = $columns;
        $page = intval($this->_context->page);
        $page = ($page < 1) ? 1 : $page;
        $articles->limitPage($page, 10);
        $this->_view['pagination'] = $articles->getPagination();

        $reject_count = count($articles->getAll());
        $this->_view['permission_id'] = $current_user->permission_id;

        $reject_count = count($articles->getAll());
        $this->_view['articles'] = $articles;
        $this->_view['reject_count'] = $reject_count;
        $this->_viewname = 'rejectindex';
    }
    
    function actionPreview()
    {
        if(null == $this->_app->currentuser())
        {
            return $this->_redirect(url('default/index'));
        }
        $article_id = $this->_context->article_id;
        $article = Article::find('article_id = ?', $article_id)->getOne();
        $creator = User::find('user_id = ?', $article->create_user_id)->getOne()->username;
        $this->_view['article'] = $article;
        $this->_view['creator'] = $creator;
        $this->_viewname = "htmlview";
    }

    function actionIndex()
    {
        if(null == $this->_app->currentUserObject())
        {
            return $this->_redirect(url('default/index'));
        }
        $current_user = $this->_app->currentUserObject();
        $enterprise_audit_status = $this->getEnterpriseAuditStatus($current_user);
        if($current_user->permission_id == 3)
        {
            $select = Article::find("enterprise_id = ? and article_status = ? or article_status = ?", 
                $current_user->enterprise_id, '1', '3');
            $this->_view['audit_count'] = $select->getCount();
            $select = Article::find("enterprise_id = ? and article_status = ? or article_status = ?", 
                $current_user->enterprise_id, '1', '3')->order('article_create_timestamp desc');
        }
        else
        {
            $select = Article::find("enterprise_id = ? and article_status = ?", $current_user->enterprise_id, '5');
            $this->_view['reject_count'] = $select->getCount();
            $select = Article::find("enterprise_id = ?", $current_user->enterprise_id)->order('article_create_timestamp desc');
        }
        $column_ids = Article::find("enterprise_id = ?", $current_user->enterprise_id)->setColumns("column_id")->asArray()->distinct()->getAll();
        $columns = Array(); 
        foreach($column_ids as $column_id)
        {
            $column = Column::find('column_id = ?', $column_id)->getOne();
            $columns[$column_id['column_id']] = $column->column_name;
        }
        $this->_view['columns'] = $columns;

        $page = intval($this->_context->page);
        if($page < 1) $page = 1;
        $article_per_page = 10;
        $select->limitPage($page, $article_per_page);
        $this->_view['pagination'] = $select->getPagination();
        $this->_view['enterprise_audit_status'] = $enterprise_audit_status;
        $this->_view['articles'] = $select->getAll();
        $this->_view['permission_id'] = $this->_app->currentUserObject()->permission_id;
        $this->_view['num'] = $select->getCount() > $article_per_page ? $article_per_page : $select->getCount();
        $this->_viewname = 'Index';
    }

    function actionRemove()
    {
        if(null == $this->_app->currentUser())
        {
            return $this->_redirect(url('default/index'));
        }
        if(isset($_POST['checkboxname']))
        {
            $article_id_array = $_POST['checkboxname'];
            //dump($vote_id_array);
            $id_array_string = join(",", $article_id_array);
            $sql = "delete from tianyi_articles where article_id in ( " . $id_array_string . " )";
            //dump($sql);
            $dbconn = QDB::getConn();
            $dbconn->execute($sql);
        }
        return $this->_redirectMessage(
            '文章删除',
            '文章已经成功被删除',
            url('article/Index'));
    }

    //编辑文章，原来生成的html文件需要删掉
    function dumpFileContent2StaticHtml($article_id, $article_name, $article_content)
    {
        $file_dir =  $this->_app->config('ROOT_DIR').'/static/html/' . date('Ym');
        $url_path = $this->_context->baseDir(). 'static/html/' . date('Ym');
        if(!file_exists($file_dir))
        {
            //dump($file_dir);
            mkdir($file_dir, 0777);
        }
        $file_name = $file_dir.'/'.$article_id.'.html';
        //dump($file_name);
        $html_file_fp = fopen($file_name, 'w');
        $header_str='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html><head><meta http-equiv="Content-type" content="text/html; charset=utf-8" /></head><title>';
        $html_header = "$header_str\n $article_name\n </title>\n <body>";
        $html_tail = "\n</body>\n</html>";
        fwrite($html_file_fp, $html_header.$article_content.$html_tail);
        fclose($html_file_fp);

        return $url_path.'/'.$article_id.'.html';
    }

    function actionEdit()
    {
        if(null == $this->_app->currentUser())
        {
            return $this->_redirect(url('default/index'));
        }
        $current_user = $this->_app->currentUserObject();
        $enterprise = Enterprise::find('enterprise_id = ?', $current_user->enterprise_id)->getOne();
        $columns_array = Column::find('enterprise_id = ?', $enterprise->id())->getAll();

        $article_id = $this->_context->article_id;
        $article = Article::find('article_id = ?', $article_id)->query();
        if (!$_POST)
        {
            $this->_view['columns'] = $columns_array;
            $this->_view['column_id'] = $article->column_id;
            $this->_view['article'] = $article;
            $upload_dir = $this->_context->baseDir() . PREFIX_UPLOAD_ENTERPRISE . "/$enterprise->enterprise_id";
            $this->_view['upload_dir'] = $upload_dir;
            $this->_viewname = 'edit';
        }
        else
        {
            if(isset($_POST['summary']))
            {
                $article->article_summary = trim_str($_POST['summary']);
            }
            if(isset($_POST['article_column']) && null != $_POST['article_column'])
            {
                $article->column_id = $_POST['article_column'];
            }
            else
            {
                $article->column_id = 0;//
            }

            $article->article_name = trim_str($_POST['article_topic']);
            $article->article_latest_update_timestamp = time();
            $file_name = $this->dumpFileContent2StaticHtml($article->article_id, $_POST['article_topic'], $_POST['article_content']);
            $article->article_url = $file_name;
            $article->article_content = $_POST['article_content'];

            $web_site=Q::ini('appini/web_site_ip');
            $content_image = $_POST['content_image'];
            if($content_image && !$article->article_isbanner)
            {
                $basedir = LOCAL_ARTICLE_ICON_DIR;
                $image = fetch_and_resize_img($content_image, ICON_WIDTH, ICON_HEIGHT, $basedir);
                $article->article_icon = $web_site . $this->_context->baseDir() . '/'. $image;
            }
            if(isset($_POST['uploadpic']))
            {
                
                $uploadpic = $_POST['uploadpic'];
                $article->article_icon = $web_site . $uploadpic;
            }
            $article->article_isbanner = 0;
            if(isset($_POST['banner']) && $_POST['banner'] == 'on')
            {
                $article->article_isbanner = 1;
            }
            $ret = $this->getEnterpriseAuditStatus($current_user);
            if(!$ret)
            {
                $this->article_status = 4;
            }
            $article->save();
            return $this->_redirectMessage(
                '编辑文章',
                '文章编辑成功',
                url('article/PreviewArticle', array('article_id' => $article->id())));
        }
    }
    
    function actionPreviewArticle()
    {
        if(null == $this->_app->currentUser())
        {
            return $this->_redirect(url('default/Index'));
        }
        $current_user = $this->_app->currentUserObject();
        if(2 != $current_user->permission_id)
        {
            return $this->_redirect(url('default/index'));
        }
        $article_id = $this->_context->article_id;
        $article = Article::find('article_id = ?', $article_id)->getOne();
        $url = Q::ini('appini/web_site_ip').$article->article_url;

        $this->_view['article_url'] = $url;
        $this->_view['article'] = $article;
        $this->_viewname = 'previewarticle';
    }

    function actionAdd()
    {
        if(null == $this->_app->currentUser())
        {
            return $this->_redirect(url('default/Index'));
        }
        $current_user = $this->_app->currentUserObject();
        if(2 != $current_user->permission_id)
        {
            return $this->_redirect(url('default/index'));
        }
        $enterprise = Enterprise::find('enterprise_id = ?', $current_user->enterprise_id)->getOne();
        $columns_array = Column::find('enterprise_id = ?', $enterprise->id())->getAll();
        $column_count = Column::find('enterprise_id = ?',  $current_user->enterprise_id)->all()->getCount();
        if (!$this->_context->isPOST())
        {
            if(!$column_count)
            {
                return $this->_redirectMessage('提示', '请增加栏目', url('column/insert'));
            }
        }
        else
        {
            try
            {
                $article = new Article();
                $article->column_id = $_POST['article_column'];
                $article->article_name = trim_str($_POST['article_topic']);
                $article->article_content = $_POST['article_content'];
                $article->enterprise_id = $enterprise->enterprise_id;
                $article->article_summary = trim_str($_POST['summary']);
                $article->create_user_id = $current_user->user_id;
                $article->audit_user_id = $current_user->user_id;
                $create_time = time();
                $article->article_create_timestamp = $create_time;
                $article->article_latest_update_timestamp = $create_time;
                $article->article_url='';
                $article->save();
                $file_name = $this->dumpFileContent2StaticHtml($article->id(), 
                $article->article_name,
                $article->article_content);
                $article->article_isbanner = 0;
                if(isset($_POST['banner']) && $_POST['banner'] == 'on')
                {
                    $article->article_isbanner = 1;
                }

                $ret = $this->getEnterpriseAuditStatus($current_user);
                if(!$ret)
                {
                    $article->article_status = 4;
                }

                $article->article_url = $file_name;
                $web_site=Q::ini('appini/web_site_ip');
                $content_image = $_POST['content_image'];
                $uploadpic="";
                if(isset($_POST['uploadpic']))
                {
                    $uploadpic = $_POST['uploadpic'];
                }
                $default_logo = $web_site . $this->_context->baseDir().'static/const_img/default.png';

                $col = Column::find('column_id = ?', $article->column_id)->query();
                $article->article_icon = $default_logo;
                //如果栏目设置了图片，则使用为默认图片
                if(strlen($col->column_logo) > 0)
                {
                    $article->article_icon = $col->column_logo;
                }
                if($content_image && !$article->article_isbanner)
                {
                    $basedir = LOCAL_ARTICLE_ICON_DIR;
                    $image = fetch_and_resize_img($content_image, ICON_WIDTH, ICON_HEIGHT, $basedir);
                    $article->article_icon = $web_site . $this->_context->baseDir() . $image;
                }
                if($uploadpic)
                {
                    $article->article_icon = $web_site.$uploadpic;
                }
                $article->save();
                return $this->_redirectMessage(
                    '发布文章',
                    '文章发布成功',
                    url('article/PreviewArticle', array('article_id' => $article->id())));
            }
            catch (Exception $ex)
            {
                return $this->_redirectMessage(
                    '发布文章出错',
                    dump($ex),
                    url('article/index'));
            }
        }
        // 将表单对象传递给视图
        $upload_dir = $this->_context->baseDir() . PREFIX_UPLOAD_ENTERPRISE . "/$enterprise->enterprise_id";
        $this->_view['enterprise_id'] = $current_user->enterprise_id;
        $this->_view['upload_dir'] = $upload_dir;
        $this->_view['columns'] = $columns_array;
    }

    function actionaddarticleaccesscount()
    {
        if(!isset($this->_context->article_url))
        {
            return 0;
        }
        //echo "article_url:".$this->_context->article_url.'<br/>';
        
        $article_id = strrchr ($this->_context->article_url, '/');
        $article_dot_pos = strrpos($article_id, '.');
        
        if($article_dot_pos == false)
        {
            return 0;
        }
        $article_id = substr($article_id, 1, ($article_dot_pos-1));
        
        //echo "article_id:".$article_id;
        $article = Article::find('article_id = ?', $article_id)->query();
        //echo '$article->article_url:'.$article->article_url;
        if( isset($article->article_id) && $article_id == $article->article_id)
        {
            $article->read_count++;
            $article->save();
        }
        return 0;
    }
}


